﻿Imports System.IO

'File Search class. can be used to search files
Public Class FileSearch
    Public FileSpec As String
    Public LookIn As String
    Public SearchSubFolders As Boolean

    Protected files As New List(Of FileInfo)

    ''' <summary>
    '''     Creates a new FileSearch class with the required details
    ''' </summary>
    ''' <param name="LookIn" type="String">
    '''     <para>
    '''         the path to look for files
    '''     </para>
    ''' </param>
    ''' <param name="FileSpec" type="String">
    '''     <para>
    '''         file details to look, For example *.exe for finding all exe files.
    '''     </para>
    ''' </param>
    ''' <param name="SearchSubFolders" type="Boolean">
    '''     <para>
    '''         Wether to look for files is subfolders
    '''     </para>
    ''' </param>
    Public Sub New(ByVal LookIn As String, _
            ByRef FileSpec As String, _
            ByVal SearchSubFolders As Boolean)
        Me.FileSpec = FileSpec
        Me.LookIn = LookIn
        Me.SearchSubFolders = SearchSubFolders
    End Sub

    ''' <summary>
    '''     The main function that is to be executed to get the list of files
    ''' </summary>
    ''' <returns>
    '''     A System.Collections.Generic.List(Of System.IO.FileInfo) value...
    ''' </returns>
    Public Function Execute() As List(Of FileInfo)
        ' Search for matching files.
        Search(LookIn)
        Return files
    End Function

    Private Sub Search(ByVal Path As String)

        Try
            Dim localDir As New DirectoryInfo(Path)
            ' Handle subfolders, if required.
            If Me.SearchSubFolders Then
                For Each directory As DirectoryInfo In localDir.GetDirectories
                    Search(directory.FullName)
                Next
            End If

            ' Search for matching file names.
            Dim localFiles As FileInfo() = localDir.GetFiles(Me.FileSpec)
            files.AddRange(localFiles)

        Catch ex As UnauthorizedAccessException
            ' Don't do anything at all
        End Try
    End Sub
End Class
